<template>
	<div class="article-upload">
		<!-- 标题区域 -->
		<div class="form-group title-section">
			<label for="title" class="title-label"><strong>文章标题</strong></label>
			<input type="text" class="form-control title-input" id="title" v-model="article.title"
				placeholder="请输入文章标题">
		</div>

		<!-- 内容区域 -->
		<div class="form-group content-area">
			<label for="content" class="content-label"><strong>文章内容</strong></label>
			<textarea class="form-control content-input" contenteditable="true" id="content" v-model="article.content"
				@input="adjustTextareaHeight" placeholder="请输入文章内容" ref="contentTextarea"></textarea>
		</div>

		<!-- 标签选择区域 -->
		<TagSelector v-model="article.tags" label="目标用户标签" />

		<!-- 图片和视频上传区域 -->
		<div class="upload-grid" :class="gridClass">
			<div v-for="(file, index) in files" :key="index" class="upload-item" @click="previewImage(file.url)">
				<img v-if="isImage(file)" :src="file.url" alt="Uploaded file" class="uploaded-file">
				<video v-else-if="isVideo(file)" :src="file.url" controls class="uploaded-file"></video>
				<button @click.stop="removeFile(index)" class="remove-button">删除</button>
			</div>
			<!-- 添加图片按钮 -->
			<div v-if="showAddImage" class="upload-item add-item" @click="addFile('image')">
				<i class="fas fa-plus">添加图片</i>
			</div>
			<!-- 添加视频按钮 -->
			<div v-if="showAddVideo" class="upload-item add-item" @click="addFile('video')">
				<i class="fas fa-plus">添加视频</i>
			</div>
		</div>

		<!-- 提交按钮 -->
		<div class="submit-section">
			<button class="btn btn-primary submit-button" @click="submitArticle">提交文章</button>
		</div>
	</div>
</template>

<script>
import TagSelector from '@/components/TagSelector/TagSelector.vue';

export default {
	components: {
		TagSelector
	},
	data() {
		return {
			article: {
				article_type: 0, // 默认为文章类型
				title: '',
				content: '',
				tags: []
			},
			files: [],
			uploadedFileIds: [],
			gridClass: 'default-grid-class',
			showAddImage: true, // 控制是否显示添加图片按钮
			showAddVideo: true  // 控制是否显示添加视频按钮
		};
	},
	methods: {
		addFile(type) {
			if (type === 'image') {
				// 校验图片数量是否已达上限
				const currentImageCount = this.files.filter(file => file.type.startsWith('image/')).length;
				if (currentImageCount >= 9) {
					uni.showToast({
						title: "最多只能上传9张图片",
						icon: "none"
					});
					return;
				}

				// 使用微信小程序的 API 选择图片
				wx.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						tempFilePaths.forEach(path => {
							this.files.push({
								url: path,
								type: 'image/jpeg'
							}); // 假设图片类型为 image/jpeg
						});
						this.article.article_type = 0; // 设置建议类型为文章
						this.showAddVideo = false; // 隐藏添加视频按钮
					}
				});
			} else if (type === 'video') {
				// 使用微信小程序的 API 选择视频
				wx.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					success: (res) => {
						this.files.push({
							url: res.tempFilePath,
							type: 'video/mp4'
						}); // 假设视频类型为 video/mp4
						this.article.article_type = 1; // 设置建议类型为视频
						this.showAddImage = false; // 隐藏添加图片按钮
						this.showAddVideo = false; // 隐藏添加视频按钮
					}
				});
			}
		},
		removeFile(index) {
			// 删除文件逻辑
			this.files.splice(index, 1);
			// 如果没有文件了，恢复按钮显示状态
			if (this.files.length === 0) {
				this.showAddImage = true;
				this.showAddVideo = true;
				this.article.article_type = 0; // 默认设置为文章类型
			}
		},
		isImage(file) {
			return file.type.startsWith('image/');
		},
		isVideo(file) {
			return file.type.startsWith('video/');
		},
		submitArticle() {
			// 检查必填字段
			if (!this.article.title.trim()) {
				uni.showToast({
					title: '请输入文章标题',
					icon: 'none'
				});
				return;
			}
			
			if (!this.article.content.trim()) {
				uni.showToast({
					title: '请输入文章内容',
					icon: 'none'
				});
				return;
			}

			// 如果没有文件，直接提交文章信息
			if (this.files.length === 0) {
				this.sendArticleInfo();
				return;
			}

			// 有文件时，先上传文件
			this.uploadedFileIds = []; // 清空已上传的文件 URL 数组
			this.uploadNextFile(0); // 从第一张图片开始上传
		},
		uploadNextFile(index) {
			if (index >= this.files.length) {
				// 所有文件上传完毕，发送文章信息
				console.log("所有文件上传完毕")
				this.sendArticleInfo();
				return;
			}

			// 显示上传中（只在有文件时显示）
			if (index === 0 && this.files.length > 0) {
				uni.showLoading({
					title: '上传中...',
					mask: true,
				});
			}

			// 生成唯一的文件名，根据文件类型选择目录
			const file = this.files[index];
			const isVideo = this.isVideo(file);
			const subDir = isVideo ? 'video' : 'image';
			const uniqueName = this.$requests.generateUniqueFileName();
			const fileExtension = file.url.split('.').pop() || (isVideo ? 'mp4' : 'jpg');
			const uniqueFileName = `advice/${subDir}/${uniqueName}.${fileExtension}`;

			this.$requests.uploadFile({
				filePath: this.files[index].url,
				name: uniqueFileName,
				success: (res) => {
                    const ok = (res && typeof res.statusCode === 'number' && res.statusCode >= 200 && res.statusCode < 300)
                        || !!res.fileID
                        || (res && res.data && res.data.file_id);
                    if (ok) {
                        const fileId = res.fileID || (res.data && res.data.file_id);
                        this.uploadedFileIds.push(fileId);
                        this.uploadNextFile(index + 1); // 上传下一张图片
                    } else {
						uni.hideLoading();
                        console.error('上传失败:', res);
						uni.showToast({
							title: '上传失败，请重试',
							icon: 'none',
						});
                    }
				},
				fail: (err) => {
					uni.hideLoading();
					console.error("failed to upload", err);
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none',
					});
				},
			});
		},
		sendArticleInfo() {
			console.log('提交文章信息，文件URLs:', this.uploadedFileIds)
			
			// 显示提交中状态
			uni.showLoading({
				title: '提交中...',
				mask: true,
			});
			
			this.$request({
				url: "/article/send/",
				method: "POST",
				data: {
					article_type: this.article.article_type,
					title: this.article.title,
					content: this.article.content,
					tags: this.article.tags || [],
					file_urls: this.uploadedFileIds || [] // 上传的文件 URL 数组，没有文件时为空数组
				},
				success: (response) => {
					if (response.statusCode === 200) {
						console.log('文章提交成功:', response);
						uni.hideLoading();
						uni.showToast({
							title: '提交成功',
							icon: 'success',
						});
						// 成功后返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 600);
					} else {
						uni.hideLoading();
						console.error('文章提交失败:', response);
						uni.showToast({
							title: '提交失败，请重试',
							icon: 'none',
						});
					}
				},
				fail: (error) => {
					uni.hideLoading();
					console.error('文章提交失败:', error);
					uni.showToast({
						title: '提交失败，请检查网络',
						icon: 'none',
					});
				},
			})
			this.uploadedFileIds = []
		},
		previewImage(url) {
			wx.previewImage({
				current: url, // 当前显示图片的链接
				urls: this.files.map(file => file.url) // 需要预览的图片链接列表
			});
		},
		adjustTextareaHeight() {
			const textarea = this.$refs.contentTextarea;
			if (textarea) {
				// 重置高度以正确计算滚动高度
				textarea.style.height = 'auto';

				// 动态设置高度，限制最大高度为 400px
				if (textarea.scrollHeight <= 400) {
					textarea.style.height = textarea.scrollHeight + 'px';
				} else {
					textarea.style.height = '400px'; // 达到最大高度后固定
				}
			}
		}
	}
};
</script>

<style>
	.article-upload {
		max-width: 600px;
		margin: 0 auto;
		padding: 20px;
		border: 1px solid #ccc;
		border-radius: 10px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		background-color: #fff;
	}

	/* 标题区域 */
	.title-section {
		margin-bottom: 25px;
	}

	.title-label {
		font-size: 18px;
		color: #333;
		margin-bottom: 10px;
		display: block;
	}

	.title-input {
		font-size: 16px;
		padding: 12px;
		border: 2px solid #ddd;
		border-radius: 5px;
		transition: border-color 0.3s;
		width: calc(100% - 20px);
		/* 确保宽度与右边界距一致 */
		margin-right: 10px;
		/* 与右边界保持一定距离 */
	}

	.title-input:focus {
		border-color: #007bff;
		outline: none;
	}

	/* 内容区域 */
	.content-area {
		margin-bottom: 25px;
	}

	.content-label {
		font-size: 18px;
		color: #333;
		margin-bottom: 10px;
		display: block;
	}

	.content-input {
		width: calc(100% - 20px);
		font-size: 14px;
		line-height: 1.6;
		border: 1px solid #ddd;
		border-radius: 5px;
		background-color: #f9f9f9;
		resize: none;
		/* 禁用手动调整大小 */
		min-height: 150px;
		/* 设置最小高度 */
		max-height: 400px;
		/* 设置最大高度 */
		overflow-y: auto;
		/* 超出最大高度时显示滚动条 */
		transition: border-color 0.3s;
		padding: 10px;
		margin-right: 10px;
		box-sizing: content-box;
	}

	.content-input:focus {
		border-color: #007bff;
		outline: none;
	}


	/* 图片上传区域 */
	.upload-grid {
		display: grid;
		grid-template-columns: repeat(3, minmax(100px, 1fr));
		gap: 15px;
		margin-bottom: 25px;
	}

	.upload-item {
		position: relative;
		border: 2px dashed #ddd;
		border-radius: 5px;
		height: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		transition: border-color 0.3s;
	}

	.upload-item:hover {
		border-color: #007bff;
	}

	.upload-item.add-item {
		background-color: #e9ecef;
		color: #555;
		font-size: 20px;
		text-align: center;
	}

	.uploaded-file {
		max-width: 100%;
		max-height: 100%;
		object-fit: cover;
		border-radius: 5px;
	}

	.remove-button {
		position: absolute;
		top: 5px;
		right: 5px;
		background-color: red;
		color: white;
		border: none;
		padding: 5px 10px;
		border-radius: 3px;
		cursor: pointer;
		font-size: 12px;
	}

	/* 提交按钮 */
	.submit-section {
		text-align: center;
	}

	.submit-button {
		padding: 12px 25px;
		font-size: 16px;
		color: #fff;
		background-color: #007bff;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.submit-button:hover {
		background-color: #0056b3;
	}

	/* 建议类型选择样式 */
	.type-selection {
		display: flex;
		justify-content: space-between;
		margin-bottom: 25px;
	}

	.type-button {
		padding: 10px 20px;
		font-size: 16px;
		border: 1px solid #ccc;
		border-radius: 5px;
		cursor: pointer;
		background-color: #f9f9f9;
		transition: background-color 0.3s, border-color 0.3s;
	}

	.type-button.active {
		background-color: #007bff;
		color: #fff;
		border-color: #007bff;
	}

	.type-button:hover {
		border-color: #007bff;
	}

	/* 响应式布局 */
	@media (max-width: 768px) {
		.article-upload {
			padding: 15px;
		}

		.title-input,
		.content-input {
			font-size: 14px;
		}

		.upload-grid {
			grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
		}

		.submit-button {
			padding: 10px 20px;
			font-size: 14px;
		}
	}
</style>